<?php
/*
 * @Author       : chaihao
 * @Date         : 2020-06-01 10:58:11
 * @FilePath     : /commands/Validator.php
 */

namespace app\commands;

use app\commands\Helper;

class Validator extends \Illuminate\Validation\Factory
{

    private static $message = 'ok';
    private static $headers =
    [
        'e' => 'rules/data is empty',
        'na' => 'rules/data is not a array'
    ];

    /***
     * 创建实例
     *
     * @return \Illuminate\Validation\Factory
     */
    public static function getInstance()
    {
        static $validator = null;
        if ($validator === null) {
            $test_translation_path = __DIR__ . '/lang';
            $test_translation_locale = 'en';
            $translation_file_loader = new \Illuminate\Translation\FileLoader(new \Illuminate\Filesystem\Filesystem, $test_translation_path);
            $translator = new \Illuminate\Translation\Translator($translation_file_loader, $test_translation_locale);
            $validator = new \Illuminate\Validation\Factory($translator);
        }
        return $validator;
    }


    /**
     * 验证封装类
     *
     * @param array $data 验证数据
     * @param array $rules 验证规则
     * @return boolean|array 验证通过返回 false 不通过 抛出参数错误异常array('code'=>105,'message'=>'参数错误描述')
     */
    public static function validator($data, $rules, $messages = array(), $ajax = 1)
    {
        $validator = self::getInstance()->make($data, $rules, $messages);
        if ($validator->fails()) {
            foreach ($validator->messages()->all() as $message) {
                Helper::right_out($data, array('code' => -1, 'message' => $message));
            }
        }
    }
}
